<template>

    <div>
        <el-card style="border-radius: 12px; height: 85vh;">
            <!-- 自能展示本人的任务 -->
            <div style="display: flex; flex-direction: row;">
                <!-- 左边的功能 -->
                <div>
                    <el-button style="margin-bottom: 10px;"><el-icon>
                            <PriceTag />
                        </el-icon>我的任务</el-button>
                    <el-button type="info" style="margin-bottom: 10px;" @click="exportData"><el-icon>
                            <Download />
                        </el-icon>导出任务</el-button>
                    <div>
                        <el-table :data="data.taskTableData" style="width: 1000px" height="750" highlight-current-row>
                            <el-table-column label="发布类型" prop="formType" width="120" />
                            <el-table-column label="任务级别" prop="level" width="120" />
                            <el-table-column label="发布分类" prop="type" width="120" />
                            <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip="ellipsis"
                                width="120" />
                            <el-table-column label="开始时间" prop="startTime" width="120">
                                <template #default="scope">
                                    {{ scope.row.startTime.substring(0, 11) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="结束时间" prop="stopTime" width="120">
                                <template #default="scope">
                                    {{ scope.row.stopTime.substring(0, 11) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="任务描述" prop="description" show-overflow-tooltip="ellipsis"
                                width="170" />
                            <el-table-column fixed="right" label="选择操作" min-width="130">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" @click="toggleSelect(scope.row)">
                                        {{ data.selectedTaskId === scope.row.id ? '✔' : '选中' }}
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

                <!-- 分界线 -->
                <div style="height: 100vh;border: 2px solid #DDDEE0; width: 1px;margin-left: 15px;border-radius: 12px;">
                </div>


                <!-- 右边的功能 -->
                <div style="background-color: #F3F3F3; height: 800px; width: 100%; margin-left: 10px;">
                    <el-button style="margin-bottom: 5px;"><el-icon>
                            <Stamp />
                        </el-icon>接 收 人</el-button>
                    <el-table :data="filterTableData" style="width: 100%" height="735">
                        <!-- height="" -->
                        <el-table-column label="联 系 人" prop="name" />
                        <el-table-column label="职位" prop="positionId">
                            <template #default="scope">
                                <el-tag type="primary" v-if="scope.row.positionId === 1">管理员</el-tag>
                                <el-tag type="primary" v-if="scope.row.positionId === 2">总经理</el-tag>
                                <el-tag type="primary" v-if="scope.row.positionId === 3">经理</el-tag>
                                <el-tag type="primary" v-if="scope.row.positionId === 4">员工</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column align="right">
                            <template #header>
                                <el-input v-model="data.search" size="small" placeholder="搜 索 联 系 人" />
                            </template>
                            <template #default="scope">
                                <el-button size="small" @click="sendMsg(scope.$index, scope.row)">
                                    <el-icon style="margin-right: 2px;">
                                        <List />
                                    </el-icon>发送
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </el-card>
    </div>


    <!-- 弹出输入框 -->
    <el-dialog v-model="data.showDialogMsg" :title="data.recipient" width="30%" :rows="10" @open="scrollToBottom"
        :style="{ position: 'fixed', bottom: '20px', right: '38px' }" :custom-class="'dialog-custom-class'">
        <!-- 聊天的内容 对话内容 -->
        <div ref="messageContainer" class="chat-container" style="">
            <div v-for="message in data.messages" :key="message.id"
                :class="['message-' + (message.from === 'me' ? 'right' : 'left')]">
                <span v-show="message.text">{{ message.text }}</span>
                <span v-show="message.fileName" style="color: #FFFFFF;cursor: pointer;" v-if="message.fileName && ['.png', '.jpg', '.jpeg'].some(extension => message.fileName.endsWith(extension)) == false ? true : false" @click="downloadFile(message.id)">{{ message.fileName }}</span>
                <span v-if="message.fileName && ['.png', '.jpg', '.jpeg'].some(extension => message.fileName.endsWith(extension))"><el-image style="width: 100px; height: 100px" :src="data.imageUrl + message.id" :fit="fit" @click="downloadFile(message.id)"></el-image><br></span>
            </div>
        </div>
        <!-- 上传U盘文件的功能 -->
        <el-icon style="cursor: pointer; margin-top: 5px;" @click="triggerFileInput"><FolderOpened /></el-icon>
        <input type="file" ref="fileInput" @change="handleFileUpload" style="margin-bottom: 15px; position: absolute; left: -99999px;top: -99999px;">
        <!-- 聊天的输入框 -->
        <el-input v-model="data.form.content" placeholder="请输入聊天内容" type="textarea" resize="none"
            style="margin-bottom: 15px;"></el-input>
        <span class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="sendMsgInfo">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 将选中的任务发送给 用户的弹窗 -->
    <el-dialog v-model="data.sendTaskTip" title="任务提示框" width="500">
        <span><span style="color: red;">确定发送你选中的任务吗 </span>?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="data.sendTaskTip = false">取消</el-button>
                <el-button type="primary" @click="sendTask">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>


</template>

<script setup>
import { computed, reactive, ref } from 'vue';
import { download, selectAllPeople, selectAllTask, selectMessagesUserConversations, sendMessageByNameAndRecipient, sendSpecialMessage } from '@/api/interaction';
import { ElMessage, ElMessageBox } from 'element-plus';
import { List, Stamp, PriceTag, Download, FolderOpened } from "@element-plus/icons-vue"; //导入按钮的ui图标
import { nextTick } from 'vue';
import { useUserStore } from '@/stores/user';

const data = reactive({
    tableData: [], //存放联系人
    taskTableData: [], //存放任务
    search: '', // 联系人搜索名字
    showDialogMsg: false, //输入信息的聊天弹窗
    form: {},
    messages: [], //展示聊天信息的数组
    sender: '', //接收人
    recipient: '', //发送人

    selectedTaskId: null, //选中的任务id

    sendTaskTip: false,

    fileName: '', // 文件夹的名称

    imageUrl: 'http://localhost:8888/message/send/', //展示图片的URL
    

})


const fileInput = ref(null) //上传文件的输入框 被隐藏起来

const messageContainer = ref()  //控制对话框的聊天内容 滚动

function triggerFileInput() {
    fileInput.value.click()// 触发文件输入框的点击事件
}

//聊天功能 点击 文件下载
const downloadFile = (id) => {
    window.open(`http://localhost:8888/message/send/${id}`)
}

//让聊天返回到最下面
const scrollToBottom = () => {
    if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
}

//导出文件的函数
const exportData = () => {
    ElMessageBox.confirm("你确认导出当前任务信息吗?", '导出', { type: 'warning', cancelButtonText: '取消', confirmButtonText: '确认', showClose: false }).then(() => {
        window.open('http://localhost:8888/interaction/export')
    }).catch()

}

// 处理格式造成的一些问题
const extractChineseAndNumbers = (text) => {
    // 使用正则表达式匹配中文字符和数字
    text = text.replace(/<[^>]*>?/gm, '') // 移除<style>标签内的内容
    const regex = /[\u4e00-\u9fa5\u0030-\u0039]+/g
    const matches = text ? text.match(regex) : null
    // 将匹配到的中文字符和数字数组连接成一个字符串
    return matches ? matches.join('') : ''
}

const toggleSelect = (row) => {
    if (data.selectedTaskId === row.id) {
        data.selectedTaskId = null 
        data.form.content = ''
    } else {
        data.selectedTaskId = row.id;
    }
    // 使用正则表达式匹配中文字符和数字
    const str = extractChineseAndNumbers(String(row.context));
    data.form.content = '任务内容：' + str
}


//处理文件上传   聊天功能中点击文件上传的功能 ...
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const fileContent = e.target.result
      const blob = new Blob([fileContent], {type: 'application/octet-stream'})
      data.form.file = blob
      data.fileName = file.name
      data.form.fileName = file.name
      sendMsgInfo() //调用发送功能
    }
    reader.readAsArrayBuffer(file)
  }
}


// 筛选逻辑
const filterTableData = computed(() =>
    data.tableData.filter((item) =>
        !data.search || item.name.toLowerCase().includes(data.search.toLowerCase())
    )
)

//发送选中的任务
const sendTask = async () => {
    data.sendTaskTip = false
    console.log(data.recipient); //接受者
    data.form.sender = data.sender
    data.form.recipient = data.recipient
    await sendMessageByNameAndRecipient(data.form).then(res => {
        if (res.data.code == '200') {
            ElMessage.success('发送成功')
            data.selectedTaskId = null;
        } else {
            ElMessage.error('发送失败')
        }
        data.form.content = ''
    })

}




//点击发送按钮 函数
const sendMsg = async (index, row) => {
    const userObj = useUserStore()
    let loggedder = userObj.user.name;
    data.sender = loggedder
    data.recipient = row.name
    //判断是否发送任务内容 [选中的任务]
    if (data.selectedTaskId !== null) {
        //发送任务 打开任务发送的提示框 ---- 逻辑
        data.sendTaskTip = true
    } else {
        data.form.content = ''
        data.showDialogMsg = true
        await selectMessagesUserConversations(loggedder, row.name).then(res => {
            //根据时间进行排序
            data.messages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)))
            data.messages = data.messages.map(item => ({
                id: item.id,
                from: item.sender === loggedder ? 'me' : 'them',
                text: item.content,
                fileName: item.fileName 
                // isImage: ['.png', '.jpg', '.jpeg'].some(extension => item.fileName.endsWith(extension)) // 检查是否为图片文件
            }))
            data.messages = data.messages.reverse()
        })
    }

    nextTick(() => { //确保自动下滑聊天对话框最下面
        scrollToBottom()
    })
}


// const fileContent = FileReader.result
// const base64String = btoa(String.fromCharCode(...new Uint8Array(fileContent)))
// data.form.file = base64String
//点击发送确定的 按钮
//还要实现发送的文件或者图片点击能放大看到，压缩包能下载
const sendMsgInfo = async () => {
    if( data.form.file === null ){
        return ElMessage({
            type: 'info',
            message: '文件内容不能为空'
        })
    }
    data.form.sender = data.sender //发送者
    data.form.recipient = data.recipient //接收者
    if (data.form.file) {
        const formData = new FormData()
        formData.append('file', data.form.file, data.fileName,data.sender,data.recipient)
        formData.append('sender', data.sender)
        formData.append('recipient', data.recipient)
        await sendSpecialMessage(formData).then(res => {
            //上传文件的接口
            if(res.data.code == '200'){
                ElMessage.success('发送成功')
            }else{
                ElMessage.error('发送失败')
            }
            data.form.file = null
            selectMessagesUserConversations(data.sender, data.recipient).then(res => {
                data.messages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)))
                data.messages = data.messages.map(item => ({
                    id: item.id,
                    from: item.sender === data.sender ? 'me' : 'them',
                    text: item.content,
                    fileName: item.fileName,
                }))
                data.messages = data.messages.reverse()
            })
        })
        return //终止其它信息的插入
    }

    
    await sendMessageByNameAndRecipient(data.form).then(res => {
        if (res.data.code == '200') {
            selectMessagesUserConversations(data.sender, data.recipient).then(res => {
                data.messages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)))
                data.messages = data.messages.map(item => ({
                    id: item.id,
                    from: item.sender === data.sender ? 'me' : 'them',
                    text: item.content,
                    fileName: item.fileName,
                }))
                data.messages = data.messages.reverse()
            })
            ElMessage.success('发送成功')
            data.form.content = ''
            data.form.fileName = ''
            data.form.file = ''
        } else {
            ElMessage.error('发送错误')
        }
    })
    scrollToBottom() // 发送消息后滚动到底部 模仿微信 QQ 发完信息后展示聊天内容最底部
}

// 发送信息取消的函数
const cancel = () => {
    data.form.content = ''
    data.showDialogMsg = false
}

// 获取全部联系人数据
const load = () => {
    //获取联系人
    selectAllPeople().then((res) => {
        data.tableData = res.data.data
    })

    //获取所有任务 --> 未做:权限只能是自的
    selectAllTask().then(res => {
        data.taskTableData = res.data.data
    })
}

load()
</script>

<style scoped>
/* 输入窗口 */
.dialog-custom-class {
    position: fixed;
    bottom: 20px;
    right: 20px;
}

.message-left {
    margin-bottom: 10px;
}

.message-left span {
    display: inline-block;
    background-color: #e0e0e0;
    padding: 10px;
    border-radius: 5px;
    max-width: 60%;
    margin-left: 10px;
}

.message-right {
    margin-bottom: 10px;
    text-align: right;
}

.message-right span {
    display: inline-block;
    background-color: #cfe7ff;
    padding: 10px;
    border-radius: 5px;
    max-width: 60%;
    margin-right: 10px;
}


.chat-container {
    height: 340px;
    overflow-y: auto;
    overflow-anchor: none;
    border: 1px solid #ccc;
}

.chat-container::-webkit-scrollbar {
    display: none;
}
</style>